package ro.peoplecentric.ctc.common.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import ro.peoplecentric.ctc.common.dao.CategoryDao;
import ro.peoplecentric.ctc.common.entity.Category;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.exception.ConcurrentModificationException;
import ro.peoplecentric.ctc.common.service.CategoryService;

/**
 * {@link CategoryService} service implementation.
 * 
 * @author pguzun
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = {ApplicationException.class, DataAccessException.class})
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryDao categoryDao;

    @SuppressWarnings("unused")
    @PostConstruct
    private void init() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void saveCategory(Category category) throws ApplicationException {
        categoryDao.saveOrUpdate(category);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteCategory(Category category) throws ApplicationException {
//		 categoryDao.lockForUpdate(category);TODO the lock makes delete throw org.hibernate.NonUniqueObjectException
        Category dbCategory = categoryDao.getById(Category.class, category.getId());

        if (dbCategory == null) {
            //concurent modification exception
            throw new ConcurrentModificationException("The Category[id : " + category.getId() + "] was already deleted");
        }
        categoryDao.delete(dbCategory);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Category> getAll() {
        return categoryDao.getAll();
    }

    @Override
    public Category getById(Long id) throws ApplicationException {
        return categoryDao.getById(Category.class, id);
    }
}
